# -*- coding: utf-8 -*-
# @Date   : 2020/1/19
# @File   : AC09_E_Future3MonUpaidLoanBal_Change_Value.py
# @Author : zhaochen
'''eof
name:企业未来3个月未结清到期贷款余额_change_value
code:AC09_E_Future3MonUpaidLoanBal_Change_Value
tableName:
columnName:
groups:AC模块
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import json
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def isFloat(x):
    '''
    判断x为float类型且大于等于0
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def getRatingInfoData(code, interface=None, last=False):
    '''
    获取上次评级信息的指标值或接口数据，默认返回的格式是tuple(val, "value") 指标值和标记
    标记分为 'value':指标值 'data':数据
    :param code: 要获取的指标值的指标code
    :param interface: EC_DSJ_2D/IC_DSJ_2D/TX_CQ_DSJ
    :return:
    '''
    try:
        historyRatingInfo = json.loads(ratingRequest.get("historyRatingInfo"))
        if last:
            # 获取上次评级数据信息
            ratingInfo = historyRatingInfo.get("lastRatingInfo")
        else:
            # 获取本次评级数据
            ratingInfo = historyRatingInfo.get("ratingInfo")
        # 如果是取score 或者 ratingLevel 直接返回
        if code in ["score", "ratingLevel"]:
            score = ratingInfo.get(code)
            try:
                return float(score), "value"
            except:
                return None, None
        # 取数据类型进行判断
        dataType = ratingInfo.get("dataType")
        # 如果传回来是数据 则返回相应接口里面的数据data
        if dataType == "1":
            data = ratingInfo.get(interface).get("data")
            if isinstance(data, dict):
                return (data, "data")
            else:
                return None, None
        # 如果传回来是指标值，则通过code进行提取
        elif dataType == "2":
            val = ratingInfo.get(code)
            if val in null_type_list:
                return None, None
            else:
                try:
                    return float(val), "value"
                except:
                    return None, None
        else:
            return None, None
    except:
        return None, None

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

def dateFormat(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None
#上次评级时间
lastGmtCreateTime=dateFormat(ratingRequest.get("lastGmtCreateTime"))

def later3MonsUpaidLoanBal2D(data,RatingTime):
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    try:
        ##企业征信 【基本信息段】(ED01A)
        EDA = getTable(data,"EDA",1)
        if EDA is None:
            return None
        elif EDA==[{}] or EDA == "":
            return 0
        else:
            ED01 = getTable(EDA[0],"ED01",0)
            if ED01 is None or ED01 == "":
                return None
            elif ED01 == [{}]:
                return 0
            else:
                factor = []
                for i in ED01:
                    ED01A = getTable(i,"ED01A", 1)
                    ED01B = getTable(i, "ED01B", 1)
                    if ED01A in null_type_list or  ED01B in null_type_list:
                        factor.append(None)
                    elif ED01A == [{}] or ED01B == [{}]:
                        factor.append(0)
                    else:
                        # 账户活动状态  ED01AD01
                        ED01AD01 = ED01A[0].get('ED01AD01')
                        # 借贷业务种类大类  ED01AD05
                        ED01AD05 = ED01A[0].get('ED01AD05')
                        # 还款表现信息
                        ED01BH = ED01B[0].get('ED01BH')
                        # 到期日期
                        ED01AR02 = ED01A[0].get('ED01AR02')
                        if ED01AD01 in null_type_list or ED01AD05 in null_type_list or ED01AR02 in null_type_list:
                            factor.append(None)
                        else:
                            if ED01AD01 == '1' and ED01AD05 == '11':
                                if dateFormat(ED01AR02) is not None:
                                    future3Months = RatingTime + datetime.timedelta(days=3 * 30)
                                    if RatingTime< dateFormat(ED01AR02) <= future3Months:
                                        if ED01BH is None:
                                            factor.append(None)
                                        elif ED01BH == [{}]:
                                            factor.append(0)
                                        else:
                                            tmp = []
                                            for i in ED01BH:
                                                # 余额
                                                ED01BJ01 = i.get('ED01BJ01')
                                                if isFloat(ED01BJ01):
                                                    tmp.append(float(ED01BJ01))
                                                else:
                                                    tmp.append(None)
                                            tmp = filter(lambda x:x is not None, tmp)
                                            if len(tmp) == 0:
                                                factor.append(None)
                                            else:
                                                factor.append(sum(tmp))
                                    else:
                                        factor.append(0)
                                else:
                                    factor.append(None)
                            else:
                                factor.append(0)
                factorNotNone = filter(lambda x: x is not None, factor)
                if len(factorNotNone) == 0:
                    return None
                else:
                    return sum(factorNotNone)
    except:
        return None

def getTable1d(data, table_Name):
    try:

        data = data.get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}] #ReportNo EC是大写 IC 是reportNo 小写
            if isinstance(data, list) and len(data) == 1 and data[0]['ReportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def Later3MonsUpaidLoanBalPre1D(data, tableName,RatingTime):
    loanInfo = getTable1d(data, tableName)
    if loanInfo is None:
        return None
    elif loanInfo == [{}]:
        return 0.0
    else:
        flag = []
        bal_sum = 0
        for i in loanInfo:
            if i.get('ReportNo') not in null_type_list:
                if i.get('Duebillsum') not in null_type_list and i.get('Duebillterminatedate') not in null_type_list \
                       and dateFormat(i.get('Duebillterminatedate')) is not None:
                    bal =  i.get('Duebillbalance')
                    terminatedate = i.get('Duebillterminatedate')
                    terminatedate = dateFormat(terminatedate)
                    # 左开右闭
                    if 0 < (terminatedate - RatingTime).days <= 3 * 30:
                        try:
                            bal = float(bal)
                        except:
                            bal = 0
                        bal_sum += bal
                else:
                    flag.append(None)
            else:
                flag.append(None)
        if len(flag) == len(loanInfo):
            bal_sum = None
        return bal_sum

def later3MonsUpaidLoanBal1D(data):
    ECRUnpaidNormalLoanInfo = Later3MonsUpaidLoanBalPre1D(data, tableName='ECRUnpaidNormalLoanInfo',RatingTime=lastGmtCreateTime)
    ECRUnpaidSMLoanInfo = Later3MonsUpaidLoanBalPre1D(data, tableName='ECRUnpaidSMLoanInfo',RatingTime=lastGmtCreateTime)
    ECRUnpaidBadLoanInfo = Later3MonsUpaidLoanBalPre1D(data, tableName='ECRUnpaidBadLoanInfo',RatingTime=lastGmtCreateTime)
    if ECRUnpaidNormalLoanInfo is None and ECRUnpaidSMLoanInfo is None and ECRUnpaidBadLoanInfo is None:
        Factor1 = None
    else:
        if ECRUnpaidSMLoanInfo is None:
            ECRUnpaidSMLoanInfo = 0
        if ECRUnpaidNormalLoanInfo is None:
            ECRUnpaidNormalLoanInfo = 0
        if ECRUnpaidBadLoanInfo is None:
            ECRUnpaidBadLoanInfo = 0
        Factor1 = ECRUnpaidSMLoanInfo + ECRUnpaidNormalLoanInfo + ECRUnpaidBadLoanInfo
    return Factor1

def factor1():
    data, data_type = getRatingInfoData('later3MonsUpaidLoanBal2D', interface='EC_DSJ_2D', last=False)
    if data_type == 'value':
        try:
            return float(data)
        except:
            return None
    elif data_type == 'data':
        res = later3MonsUpaidLoanBal2D(data,RatingTime=datetime.datetime.now())
        return res
    else:
        return None

def factor2():
    data, data_type = getRatingInfoData('later3MonsUpaidLoanBal1D', interface='EC_DSJ', last=True)
    if data is None:
        # 如果一代的数据没有，则使用二代的数据去取
        data, data_type = getRatingInfoData('later3MonsUpaidLoanBal2D', interface='EC_DSJ_2D', last=True)
        if data_type == 'value':
            try:
                return float(data)
            except:
                return None
        elif data_type == 'data':
            res = later3MonsUpaidLoanBal2D(data,RatingTime=lastGmtCreateTime)
            return res
        else:
            return None
    else:
        if data_type == 'value':
            try:
                return float(data)
            except:
                return None
        elif data_type == 'data':
            res = later3MonsUpaidLoanBal1D(data)
            return res
        else:
            return None


def AC09_E_Future3MonUpaidLoanBal_Change_Value():
    f1 = factor1()
    f2 = factor2()
    if f1 is None or f2 is None:
        return u'缺失值'
    else:
        return f1 - f2

result = AC09_E_Future3MonUpaidLoanBal_Change_Value()